package com.cz.nongyetongv5.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mdx.mobile.dialogs.Loading;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.NewsListPagerAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.New;
import com.cz.nongyetongv5.bean.NewsTitle;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.BlueLoadingProgress;
import com.cz.nongyetongv5.custom.viewpagerindicator.TitlePageIndicator;
import com.cz.nongyetongv5.dialog.LoadingDialog;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

public class NewsListActivity extends FragmentActivity implements
		OnClickListener {

	/**
	 * 所有的标题集合
	 */
	private List<NewsTitle> titles = new ArrayList<NewsTitle>();

	// Viewpager 的指示器
	private TitlePageIndicator tpiIndicator = null;

	// ViewPager
	private ViewPager vpNewListView = null;

	/**
	 * 刷新按钮
	 */
	private ViewGroup btnRefresh = null;

	/**
	 * 刷新中进度条
	 */
	private ProgressBar pbRefresh = null;

	/**
	 * 刷新按钮文本
	 */
	private TextView tvProgress = null;

	/**
	 * 返回按钮
	 */
	private ViewGroup btnBack = null;

	/**
	 * 刷新标题Task
	 */
	private AsyncTask<String, Integer, Integer> atRefreshTitleTask = null;

	/**
	 * 自定义加载中
	 *
	 * @param savedInstanceState
	 */
	// private BlueLoadingProgress blpLoading = null;

	/**
	 * 请求的地址
	 */
	private String news_category_url = null;

	/**
	 * 当前Activity 从什么地方来
	 */
	private String from = "";

	/**
	 * 用户信息
	 */
	private User user = null;

	/**
	 * 消息接收者
	 */
	private MessageReceiver mMessageReceiver;

	/**
	 * 查找New
	 */
	private ViewGroup btnToNew;

	/**
	 * 新闻列表的状态
	 */
	private TextView titleState;

	protected LoadingDialog loadingDialog;

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(NewsListActivity.class.getName());
		registerReceiver(mMessageReceiver, filter);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.newslist);

		titleState = (TextView) findViewById(R.id.titleState);

		registerMessageReceiver();

		// 初始化viewpager
		vpNewListView = (ViewPager) findViewById(R.id.vpNewListView);

		// 初始化指示器
		tpiIndicator = (TitlePageIndicator) findViewById(R.id.tpiIndicator);

		tpiIndicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int postion) {

				NewListItemFragment fragment = (NewListItemFragment) getSupportFragmentManager()
						.getFragments().get(postion);

				fragment.refreshListView(false);

				if (fragment.getUnreadlist()) {
					titleState.setText("仅未读模式");
				} else {
					titleState.setText("全部新闻模式");

				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		// 初始化刷新按钮
		btnRefresh = (ViewGroup) findViewById(R.id.btnRefresh);
		btnRefresh.setOnClickListener(this);

		// 初始化刷新文本
		tvProgress = (TextView) btnRefresh.getChildAt(0);

		// 初始化progressbar
		pbRefresh = (ProgressBar) btnRefresh.getChildAt(1);

		// 初始化返回按钮
		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);

		// blpLoading = (BlueLoadingProgress) findViewById(R.id.blpLoading);

		// 初始化请求地址
		news_category_url = new ConfigUtil(getResources()).getPreHttpUrl()
				+ getResources().getString(R.string.download_news_category);

		/**
		 * 清除消息
		 */
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(0);

		if (getIntent() != null) {

			from = getIntent().getStringExtra("from");

			user = (User) getIntent().getExtras().get("user");

			if (user == null) {

				DialogUtil.showMessageDialog(getString(R.string.not_login),
						new OnClickListener() {

							@Override
							public void onClick(View v) {

								if ("notification".equals(from)) {

									Intent to_login = new Intent(
											NewsListActivity.this,
											LoginActivity.class);

									startActivity(to_login);

									finish();

								}

							}
						}, this);

			} else {
				if (this.atRefreshTitleTask == null
						|| this.atRefreshTitleTask.getStatus() == Status.FINISHED) {

					refresh();

					this.atRefreshTitleTask.execute();
				}
			}
		}
		this.btnToNew = (ViewGroup) findViewById(R.id.btnToNew);
		btnToNew.setOnClickListener(this);

	}

	/**
	 * 当按钮点击的时候
	 */
	@Override
	public void onClick(View v) {

		// 搜寻新新闻的时候
		if (v == btnToNew) {

			int selectPosition = vpNewListView.getCurrentItem();

			Fragment activity = getSupportFragmentManager().getFragments().get(
					selectPosition);

			if (activity != null && activity instanceof NewListItemFragment) {

				NewListItemFragment fragment = (NewListItemFragment) activity;

				fragment.setUnreadlist(!fragment.getUnreadlist());

				if (fragment.getUnreadlist()) {

					Toast.makeText(NewsListActivity.this, "已进入只显示未读新闻模式..",
							Toast.LENGTH_LONG).show();

					titleState.setText("仅未读模式");

				} else {
					Toast.makeText(NewsListActivity.this, "已进入只显示全部新闻模式..",
							Toast.LENGTH_LONG).show();
					titleState.setText("全部新闻模式");
				}

				fragment.refresh(0);

			}

		}

		// 当点击返回的时候
		if (v == btnBack) {
			doBack();
		}

		// 当点击刷新的时候
		if (v == btnRefresh) {

			// 如果标题没有则刷新标题
			if (this.titles == null || titles.size() < 1) {

				if (this.atRefreshTitleTask == null
						|| this.atRefreshTitleTask.getStatus() == Status.FINISHED) {
					refresh();
					this.atRefreshTitleTask.execute();
				}
			} else {
				// 进行子项的刷新
				int postion = vpNewListView.getCurrentItem();

				if (getSupportFragmentManager() != null
						&& getSupportFragmentManager().getFragments() != null
						&& getSupportFragmentManager().getFragments().size() > postion) {

					NewListItemFragment fragment = (NewListItemFragment) getSupportFragmentManager()
							.getFragments().get(postion);

					if (fragment != null) {
						fragment.refreshListView(true);
					}

				}

			}
		}

	}

	/**
	 * 刷新的任务
	 */
	private void refresh() {
		/**
		 * 下载类别的异步任务
		 */
		atRefreshTitleTask = new AsyncTask<String, Integer, Integer>() {

			private int responseCodeRet;

			private String responseBodyRet;

			@Override
			protected void onPreExecute() {
				// 将进度条显示出来
				toggleProgress(true);

				// 不显示ViewPager
				vpNewListView.setVisibility(View.GONE);

				// 不显示引导器
				tpiIndicator.setVisibility(View.GONE);

				// 显示等待
				// blpLoading.setVisibility(View.VISIBLE);
				//
				// blpLoading.startLoading();
				loadingDialog = new LoadingDialog(NewsListActivity.this);
				loadingDialog.setCanceledOnTouchOutside(false);
				loadingDialog.setText("正在加载");
				loadingDialog.show();

			}

			@Override
			protected Integer doInBackground(String... params) {

				HttpUtils httpUtils = HttpUtils.getInstance();

				String authUserName = new ConfigUtil(getResources())
						.getRestUsername();

				String authPassword = new ConfigUtil(getResources())
						.getRestPassword();

				httpUtils.setOnRequestExecuted(new OnRequestExecuted() {
					@Override
					public void onRequestExecuted(int responseCode,
												  String responseBody) {

						responseCodeRet = responseCode;
						responseBodyRet = responseBody;
					}
				});

				httpUtils.sendRequest(news_category_url, null, "GET", "UTF-8",
						authUserName, authPassword, user);

				return null;
			}

			@Override
			protected void onPostExecute(Integer result) {

				// 将进度条隐藏
				toggleProgress(false);

				// 不显示等待
				// blpLoading.setVisibility(View.GONE);

				// 取消loading
				// blpLoading.stopLoading();

				switch (responseCodeRet) {
					case HttpUtils.SUCCESS:

						try {
							loadingDialog.dismiss();
							JSONArray jsonArray = new JSONObject(responseBodyRet)
									.getJSONArray("result");

							titles.clear();

							int size = jsonArray.length();

							for (int i = 0; i < size; i++) {

								JSONObject jsonObject = jsonArray.getJSONObject(i);

								Integer id = jsonObject.getInt("value");
								String titleName = jsonObject.getString("name");

								titles.add(new NewsTitle(id, titleName));

							}

							vpNewListView.setAdapter(new NewsListPagerAdapter(
									getSupportFragmentManager(), titles,
									NewsListActivity.this));
							vpNewListView.setOffscreenPageLimit(titles.size());
							tpiIndicator.setViewPager(vpNewListView);

							// 显示ViewPager
							vpNewListView.setVisibility(View.VISIBLE);

							tpiIndicator.setVisibility(View.VISIBLE);

						} catch (JSONException e) {
							DialogUtil.showMessageDialog(NewsListActivity.this
											.getString(R.string.message_softerror), null,
									NewsListActivity.this);
							loadingDialog.dismiss();
						}

						break;

					case HttpUtils.TIMEOUT:
						DialogUtil.showMessageDialog(NewsListActivity.this
										.getString(R.string.message_socktimeout), null,
								NewsListActivity.this);
						break;

					case HttpUtils.NETWORK_ERR:
						DialogUtil.showMessageDialog(NewsListActivity.this
										.getString(R.string.error_no_network), null,
								NewsListActivity.this);
						break;

					case HttpUtils.UNKNOWERROR:
						DialogUtil.showMessageDialog(NewsListActivity.this
										.getString(R.string.message_softerror), null,
								NewsListActivity.this);
						break;
				}
			}

		};

	}

	/***
	 * 对进度条进行显示与否
	 */
	public void toggleProgress(boolean visible) {

		if (visible) {
			// 将文本隐藏
			tvProgress.setVisibility(View.GONE);

			pbRefresh.setVisibility(View.VISIBLE);
			// 设置为不允许点击
			btnRefresh.setClickable(false);
		} else {

			// 将文本隐藏
			tvProgress.setVisibility(View.VISIBLE);

			pbRefresh.setVisibility(View.GONE);

			// 设置为可以点击
			btnRefresh.setClickable(true);
		}

	}

	@Override
	public void onBackPressed() {
		doBack();

		super.onBackPressed();
	}

	/**
	 * 当返回的时候
	 */
	private void doBack() {

		boolean oneActivity = false;

		ActivityManager activityManager = (ActivityManager) this
				.getSystemService(Context.ACTIVITY_SERVICE);

		// 如果只有新闻列表的activity在运行
		List<RunningTaskInfo> taskList = activityManager.getRunningTasks(100);
		for (RunningTaskInfo rti : taskList) {

			if (rti.baseActivity.getPackageName().equals(this.getPackageName())) {

				if (rti.numActivities < 2) {

					oneActivity = true;

				}
			}

			break;
		}

		// 如果是从推送来的,并且只有新闻列表在运行,则返回到主页面
		if (CharsetUtil.isNotNull(from) && oneActivity) {

			Intent intent = new Intent(this, StartActivity.class);
			intent.putExtra("user", user);
			this.startActivity(intent);

		}

		setResult(1);

		this.finish();

	}

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// 取消消息接受者注册
		unregisterReceiver(mMessageReceiver);

		super.onDestroy();
	}

	/**
	 * 消息的接受者
	 */
	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (NewsListActivity.class.getName().equals(intent.getAction())) {

				int category = -1;

				String extra = intent.getStringExtra("extra");

				String username = "";

				String id = "";

				String title = "";

				String image = null;

				String date = "";

				String intro = "";

				boolean isRead = false;

				if (CharsetUtil.isNotNull(extra)) {
					try {
						JSONObject jsonObject = new JSONObject(extra);

						id = jsonObject.getJSONObject("android")
								.getString("id");

						username = jsonObject.getJSONObject("android")
								.getString("username");

						title = jsonObject.getJSONObject("android").getString(
								"title");

						date = jsonObject.getJSONObject("android").getString(
								"date");

						intro = jsonObject.getJSONObject("android").getString(
								"intro");

						category = jsonObject.getJSONObject("android").getInt(
								"category");

						if (!jsonObject.getJSONObject("android")
								.isNull("image")) {

							image = jsonObject.getJSONObject("android")
									.getString("image");
						}

						if (username.equals(user.getUsername())) {
							isRead = true;
						}

					} catch (JSONException e) {
						loadingDialog.dismiss();
					}
				}

				int currentItem = category - 1;

				String tag = titles.get(currentItem).getName();

				// 如果是当前选中的页面
				New newObj = new New(id, title, intro, date, tag, image, isRead);

				Fragment fragment = getSupportFragmentManager().getFragments()
						.get(currentItem);

				if (fragment != null) {

					NewListItemFragment newListItemFragment = (NewListItemFragment) fragment;

					newListItemFragment.addNew(newObj);

				}

			}
		}
	}

}
